#define WIN32_LEAN_AND_MEAN
#include <winsock2.h>
#include <windows.h>
#include <ws2tcpip.h>
#include <commctrl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>
#include <direct.h>
#include <process.h>
#include <shellapi.h>
#include <commdlg.h>
#include "base64.h"

// 定义 Internet Explorer 版本以确保支持 INITCOMMONCONTROLSEX
#define _WIN32_IE 0x0600

// 移除 connect 宏以避免冲突
#ifdef connect
#undef connect
#endif

#define IDC_INPUT    1001
#define IDC_SEND     1002
#define IDC_CHATLIST 1003
#define IDC_FILE     1004
#define IDC_USERNAME 1005
#define IDC_PASSWORD 1006
#define IDC_LOGIN    1007
#define IDC_REGISTER 1008

// 消息类型定义
#define MSG_TYPE_TEXT 0x01
#define MSG_TYPE_FILE 0x02
#define MSG_TYPE_LOGIN 0x03
#define MSG_TYPE_REGISTER 0x04
#define MSG_TYPE_RESPONSE 0x05
#define MSG_TYPE_PRIVATE_TEXT 0x06 // 新增私聊消息类型
#define MSG_TYPE_FILE_SEND_REQUEST 0x07
#define MSG_TYPE_FILE_RECEIVE_NOTICE 0x08

// 缓冲区大小
#define BUFFER_SIZE 5120

// 全局变量
HWND hInputEdit;
HWND hChatList;
HWND hStatus;
HWND hUsernameEdit;
HWND hPasswordEdit;
HWND hLoginWnd;  // 新增：登录窗口句柄
HWND hMainWnd;   // 新增：主窗口句柄
SOCKET clientSocket = INVALID_SOCKET;
BOOL connected = FALSE;
CRITICAL_SECTION csLog;
HFONT hFont;
float CLIENT_EDITION = 1.2;

// 客户端状态结构体
typedef struct {
    BOOL logged_in;
    wchar_t username[256];
} ClientState;

ClientState client_state = {FALSE, L""};

// 初始化网络
BOOL InitNetwork() {
    WSADATA wsaData;
    return WSAStartup(MAKEWORD(2, 2), &wsaData) == 0;
}

// 连接到服务器
BOOL ConnectToServer(const char* ip, int port) {
    struct sockaddr_in serv_addr = {0};
    serv_addr.sin_family = AF_INET;
    serv_addr.sin_port = htons(port);
    serv_addr.sin_addr.s_addr = inet_addr(ip);

    clientSocket = socket(AF_INET, SOCK_STREAM, 0);
    if (clientSocket == INVALID_SOCKET) return FALSE;

    const int result = connect(clientSocket, 
                             (const struct sockaddr*)&serv_addr,
                             (int)sizeof(serv_addr));

    if (result == SOCKET_ERROR) {
        closesocket(clientSocket);
        clientSocket = INVALID_SOCKET;
        return FALSE;
    }

    // 接收服务端版本信息
    float server_edition;
    recv(clientSocket, (char*)&server_edition, sizeof(server_edition), 0);

    // 比较版本信息
    if (CLIENT_EDITION < server_edition) {
        MessageBoxW(NULL, L"当前版本过低", L"提示", MB_OK | MB_ICONWARNING);

        // 下载新的 client-1.exe 文件
        ShellExecuteW(NULL, L"open", L"https://gitee.com/zovey-git/simple-chat-room/blob/main/client-1.exe", NULL, NULL, SW_SHOWNORMAL);
    }

    return TRUE;
}

// 发送消息
void SendMessageToServer(const char* message, unsigned char msg_type) {
    if (!connected || clientSocket == INVALID_SOCKET) return;

    // 确保消息以UTF-8编码发送
    int utf8_len = MultiByteToWideChar(CP_ACP, 0, message, -1, NULL, 0);
    wchar_t* wbuffer = (wchar_t*)malloc(utf8_len * sizeof(wchar_t));
    MultiByteToWideChar(CP_ACP, 0, message, -1, wbuffer, utf8_len);
    
    utf8_len = WideCharToMultiByte(CP_UTF8, 0, wbuffer, -1, NULL, 0, NULL, NULL);
    char* utf8_buffer = (char*)malloc(utf8_len);
    WideCharToMultiByte(CP_UTF8, 0, wbuffer, -1, utf8_buffer, utf8_len, NULL, NULL);
    
    free(wbuffer);

    // 去除多余的空字符
    while (utf8_len > 0 && utf8_buffer[utf8_len - 1] == '\0') {
        utf8_len--;
    }

    // 计算CRC32校验值
    uint32_t crc = crc32((const unsigned char*)utf8_buffer, utf8_len);

    // 消息类型标识
    char msg_with_type[BUFFER_SIZE + 2 + sizeof(uint32_t)];
    msg_with_type[0] = msg_type;
    memcpy(msg_with_type + 1, &crc, sizeof(uint32_t));
    memcpy(msg_with_type + 1 + sizeof(uint32_t), utf8_buffer, utf8_len);
    int total_length = 1 + sizeof(uint32_t) + utf8_len;
    
    free(utf8_buffer);

    int encoded_len;
    char* encoded = Base64Encode((const unsigned char*)msg_with_type, total_length, &encoded_len);
    if (encoded) {
        send(clientSocket, encoded, encoded_len, 0);
        free(encoded);
    }
}

// 登录按钮点击事件
void on_login_click() {
    wchar_t username[256];
    wchar_t password[256];
    GetWindowTextW(hUsernameEdit, username, sizeof(username) / sizeof(wchar_t));
    GetWindowTextW(hPasswordEdit, password, sizeof(password) / sizeof(wchar_t));

    // 保存账户名到 client_state
    wcscpy(client_state.username, username);

    // 将账号进行 Base64 编码
    int utf8_username_len = WideCharToMultiByte(CP_UTF8, 0, username, -1, NULL, 0, NULL, NULL);
    char* utf8_username = (char*)malloc(utf8_username_len);
    WideCharToMultiByte(CP_UTF8, 0, username, -1, utf8_username, utf8_username_len, NULL, NULL);

    int encoded_username_len;
    char* encoded_username = Base64Encode((const unsigned char*)utf8_username, utf8_username_len - 1, &encoded_username_len);

    // 将密码进行 Base64 编码
    int utf8_password_len = WideCharToMultiByte(CP_UTF8, 0, password, -1, NULL, 0, NULL, NULL);
    char* utf8_password = (char*)malloc(utf8_password_len);
    WideCharToMultiByte(CP_UTF8, 0, password, -1, utf8_password, utf8_password_len, NULL, NULL);

    int encoded_password_len;
    char* encoded_password = Base64Encode((const unsigned char*)utf8_password, utf8_password_len - 1, &encoded_password_len);

    char login_msg[BUFFER_SIZE];
    sprintf(login_msg, "%s:%s", encoded_username, encoded_password);

    SendMessageToServer(login_msg, MSG_TYPE_LOGIN);

    free(utf8_username);
    free(encoded_username);
    free(utf8_password);
    free(encoded_password);
}

// 注册按钮点击事件
void on_register_click() {
    wchar_t username[256];
    wchar_t password[256];
    GetWindowTextW(hUsernameEdit, username, sizeof(username) / sizeof(wchar_t));
    GetWindowTextW(hPasswordEdit, password, sizeof(password) / sizeof(wchar_t));

    // 将账号进行 Base64 编码
    int utf8_username_len = WideCharToMultiByte(CP_UTF8, 0, username, -1, NULL, 0, NULL, NULL);
    char* utf8_username = (char*)malloc(utf8_username_len);
    WideCharToMultiByte(CP_UTF8, 0, username, -1, utf8_username, utf8_username_len, NULL, NULL);

    int encoded_username_len;
    char* encoded_username = Base64Encode((const unsigned char*)utf8_username, utf8_username_len - 1, &encoded_username_len);

    // 将密码进行 Base64 编码
    int utf8_password_len = WideCharToMultiByte(CP_UTF8, 0, password, -1, NULL, 0, NULL, NULL);
    char* utf8_password = (char*)malloc(utf8_password_len);
    WideCharToMultiByte(CP_UTF8, 0, password, -1, utf8_password, utf8_password_len, NULL, NULL);

    int encoded_password_len;
    char* encoded_password = Base64Encode((const unsigned char*)utf8_password, utf8_password_len - 1, &encoded_password_len);

    char register_msg[BUFFER_SIZE];
    sprintf(register_msg, "%s:%s", encoded_username, encoded_password);

    SendMessageToServer(register_msg, MSG_TYPE_REGISTER);

    free(utf8_username);
    free(encoded_username);
    free(utf8_password);
    free(encoded_password);
}

// 发送按钮点击事件
void on_send_click() {
    char buffer[BUFFER_SIZE] = {0};
    GetWindowTextA(hInputEdit, buffer, sizeof(buffer));
    if (strlen(buffer) > 0) {
        unsigned char msg_type = MSG_TYPE_TEXT;
        if (strncmp(buffer, "ft=", 3) == 0) {
            msg_type = MSG_TYPE_FILE;
            char target_username[256];
            sscanf(buffer, "ft=%s", target_username);

            // 打开文件选择对话框
            OPENFILENAMEA ofn;
            char szFile[260];
            ZeroMemory(&ofn, sizeof(ofn));
            ofn.lStructSize = sizeof(ofn);
            ofn.hwndOwner = hMainWnd;
            ofn.lpstrFile = szFile;
            ofn.lpstrFile[0] = '\0';
            ofn.nMaxFile = sizeof(szFile);
            ofn.lpstrFilter = "All Files (*.*)\0*.*\0";
            ofn.nFilterIndex = 1;
            ofn.lpstrFileTitle = NULL;
            ofn.nMaxFileTitle = 0;
            ofn.lpstrInitialDir = NULL;
            ofn.Flags = OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST;

            if (GetOpenFileNameA(&ofn) == TRUE) {
                // 读取文件内容
                FILE *fp = fopen(szFile, "rb");
                if (fp != NULL) {
                    fseek(fp, 0, SEEK_END);
                    long file_size = ftell(fp);
                    fseek(fp, 0, SEEK_SET);
                    unsigned char *file_data = (unsigned char *)malloc(file_size);
                    fread(file_data, 1, file_size, fp);
                    fclose(fp);

                    // 获取文件名（包含后缀）
                    char *file_name = strrchr(szFile, '\\');
                    if (file_name == NULL) {
                        file_name = szFile;
                    } else {
                        file_name++;
                    }

                    // 计算CRC32校验值
                    uint32_t crc = crc32(file_data, file_size);

                    // 发送文件消息
                    char msg_with_type[BUFFER_SIZE + 2 + strlen(target_username) + 1 + strlen(file_name) + 1 + sizeof(uint32_t)];
                    msg_with_type[0] = MSG_TYPE_FILE;
                    memcpy(msg_with_type + 1, &crc, sizeof(uint32_t));
                    sprintf(msg_with_type + 1 + sizeof(uint32_t), "%s:%s:", target_username, file_name);
                    memcpy(msg_with_type + 1 + sizeof(uint32_t) + strlen(target_username) + 1 + strlen(file_name) + 1, file_data, file_size);
                    int total_length = 1 + sizeof(uint32_t) + strlen(target_username) + 1 + strlen(file_name) + 1 + file_size;

                    int encoded_len;
                    char *encoded = Base64Encode((const unsigned char *)msg_with_type, total_length, &encoded_len);
                    if (encoded) {
                        send(clientSocket, encoded, encoded_len, 0);
                        free(encoded);
                    }

                    free(file_data);

                    // 显示文件发送完成消息
                    wchar_t display_msg[BUFFER_SIZE];
                    swprintf(display_msg, L"文件发送完成");
                    EnterCriticalSection(&csLog);
                    SendMessageW(hChatList, LB_ADDSTRING, 0, (LPARAM)display_msg);
                    LeaveCriticalSection(&csLog);
                }
            }
        } else {
            if (buffer[0] == '/') {
                char *equal_pos = strchr(buffer, '=');
                if (equal_pos != NULL) {
                    msg_type = MSG_TYPE_PRIVATE_TEXT;
                }
            }

            SendMessageToServer(buffer, msg_type);
            SetWindowTextA(hInputEdit, "");

            // 将自己发送的消息添加到聊天列表中
            // 先将 ANSI 编码转换为宽字符
            int wlen = MultiByteToWideChar(CP_ACP, 0, buffer, -1, NULL, 0);
            wchar_t *wbuffer = (wchar_t *)malloc((wlen + 1) * sizeof(wchar_t));
            MultiByteToWideChar(CP_ACP, 0, buffer, -1, wbuffer, wlen);
            wbuffer[wlen] = L'\0'; // 添加字符串结束符

            // 再将宽字符转换为 UTF-8 编码
            int utf8_len = WideCharToMultiByte(CP_UTF8, 0, wbuffer, -1, NULL, 0, NULL, NULL);
            char *utf8_buffer = (char *)malloc(utf8_len);
            WideCharToMultiByte(CP_UTF8, 0, wbuffer, -1, utf8_buffer, utf8_len, NULL, NULL);

            // 将 UTF-8 编码的消息转换回宽字符以显示
            wlen = MultiByteToWideChar(CP_UTF8, 0, utf8_buffer, -1, NULL, 0);

            wchar_t *display_wbuffer = (wchar_t *)malloc((wlen + 1 + 2) * sizeof(wchar_t)); // 多分配 2 个字符空间用于“我:”
            swprintf(display_wbuffer, L"我:%ls", wbuffer); // 添加“我:”前缀

            EnterCriticalSection(&csLog);
            SendMessageW(hChatList, LB_ADDSTRING, 0, (LPARAM)display_wbuffer);
            LeaveCriticalSection(&csLog);

            free(wbuffer);
            free(utf8_buffer);
            free(display_wbuffer);
        }
    }
}

// 接收消息线程
DWORD WINAPI receive_message(LPVOID lpParam) {
    char buffer[BUFFER_SIZE] = {0};
    while (connected) {
        const int bytes_received = recv(clientSocket, buffer, sizeof(buffer)-1, 0);
        if (bytes_received <= 0) break;

        buffer[bytes_received] = '\0';
        
        // Base64解码
        int decoded_length;
        unsigned char *decoded_data = Base64Decode(buffer, bytes_received, &decoded_length);
        if (decoded_data != NULL) {
            if (decoded_length > 0) {
                unsigned char msg_type = decoded_data[0];
                unsigned char *actual_data = decoded_data + 1;
                int actual_length = decoded_length - 1;

                switch (msg_type) {
                    case MSG_TYPE_TEXT: {
                        // 确保正确转换UTF-8数据为宽字符
                        int wlen = MultiByteToWideChar(CP_UTF8, 0, (const char*)actual_data, actual_length, NULL, 0);
                        wchar_t* wbuffer = (wchar_t*)malloc((wlen + 1) * sizeof(wchar_t));
                        MultiByteToWideChar(CP_UTF8, 0, (const char*)actual_data, actual_length, wbuffer, wlen);
                        wbuffer[wlen] = L'\0'; // 添加字符串结束符

                        EnterCriticalSection(&csLog);
                        SendMessageW(hChatList, LB_ADDSTRING, 0, (LPARAM)wbuffer);
                        LeaveCriticalSection(&csLog);

                        free(wbuffer);
                        break;
                    }
                    case MSG_TYPE_RESPONSE: {
                        // 处理响应消息
                        int wlen = MultiByteToWideChar(CP_UTF8, 0, (const char*)actual_data, actual_length, NULL, 0);
                        wchar_t* wbuffer = (wchar_t*)malloc((wlen + 1) * sizeof(wchar_t));
                        MultiByteToWideChar(CP_UTF8, 0, (const char*)actual_data, actual_length, wbuffer, wlen);
                        wbuffer[wlen] = L'\0'; // 添加字符串结束符

                        if (wcscmp(wbuffer, L"登录成功") == 0) {
                            client_state.logged_in = TRUE;
                            MessageBoxW(NULL, L"登录成功", L"提示", MB_OK | MB_ICONWARNING);
                            // 显示主窗口，隐藏登录窗口
                            ShowWindow(hLoginWnd, SW_HIDE);
                            ShowWindow(hMainWnd, SW_SHOW);

                            // 设置窗口标题为账户名
                            wchar_t title[BUFFER_SIZE];
                            swprintf(title, L"%ls - Win32 TCP Client", client_state.username);
                            SetWindowTextW(hMainWnd, title);
                        } else if (wcscmp(wbuffer, L"该用户已登录") == 0) {
                            // 提示登录失败
                            MessageBoxW(NULL, L"该用户已登录", L"提示", MB_OK | MB_ICONWARNING);
                        } else if (wcscmp(wbuffer, L"登录失败") == 0) {
                            // 提示登录失败
                            MessageBoxW(NULL, L"账号或密码错误", L"提示", MB_OK | MB_ICONWARNING);
                        } else if (wcscmp(wbuffer, L"注册成功") == 0) {
                            // 提示注册成功
                            MessageBoxW(NULL, L"注册成功，请登录", L"提示", MB_OK | MB_ICONINFORMATION);

                            // 创建以账号名命名的文件夹
                            wchar_t folderPath[260];
                            swprintf(folderPath, L"D:\\%ls", client_state.username);
                            if (_wmkdir(folderPath) == 0) {
                                wprintf(L"Folder created: %ls\n", folderPath);
                            } else {
                                wprintf(L"Failed to create folder: %ls\n", folderPath);
                            }
                        } else if (wcscmp(wbuffer, L"注册失败，账号已存在") == 0) {
                            // 提示账号已存在
                            MessageBoxW(NULL, L"该用户已存在", L"提示", MB_OK | MB_ICONWARNING);
                        }

                        free(wbuffer);
                        break;
                    }
                    case MSG_TYPE_PRIVATE_TEXT: {
                        // 确保正确转换UTF-8数据为宽字符
                        int wlen = MultiByteToWideChar(CP_UTF8, 0, (const char*)actual_data, actual_length, NULL, 0);
                        wchar_t* wbuffer = (wchar_t*)malloc((wlen + 1) * sizeof(wchar_t));
                        MultiByteToWideChar(CP_UTF8, 0, (const char*)actual_data, actual_length, wbuffer, wlen);
                        wbuffer[wlen] = L'\0'; // 添加字符串结束符

                        EnterCriticalSection(&csLog);
                        SendMessageW(hChatList, LB_ADDSTRING, 0, (LPARAM)wbuffer);
                        LeaveCriticalSection(&csLog);

                        free(wbuffer);
                        break;
                    }
                    case MSG_TYPE_FILE: {
                        // 确保正确转换UTF-8数据为宽字符
                        int wlen = MultiByteToWideChar(CP_UTF8, 0, (const char *)actual_data, actual_length, NULL, 0);
                        wchar_t *wbuffer = (wchar_t *)malloc((wlen + 1) * sizeof(wchar_t));
                        MultiByteToWideChar(CP_UTF8, 0, (const char *)actual_data, actual_length, wbuffer, wlen);
                        wbuffer[wlen] = L'\0'; // 添加字符串结束符

                        EnterCriticalSection(&csLog);
                        SendMessageW(hChatList, LB_ADDSTRING, 0, (LPARAM)wbuffer);
                        LeaveCriticalSection(&csLog);

                        free(wbuffer);
                        break;
                    }
                }
            }

            free(decoded_data);
        }
    }

    connected = FALSE;
    closesocket(clientSocket);
    clientSocket = INVALID_SOCKET;
    if (hStatus) {
        SendMessageW(hStatus, SB_SETTEXT, 0, (LPARAM)L"Disconnected");
    }
    return 0;
}

// 登录窗口过程
LRESULT CALLBACK LoginWndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) {
    switch (message) {
    case WM_CREATE: {
        hFont = CreateFontW(14, 0, 0, 0, FW_NORMAL, FALSE, FALSE, FALSE, DEFAULT_CHARSET, OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS, DEFAULT_QUALITY, DEFAULT_PITCH | FF_SWISS, L"宋体");

        hUsernameEdit = CreateWindowExW(WS_EX_CLIENTEDGE, L"EDIT", L"",
            WS_CHILD | WS_VISIBLE | WS_BORDER | ES_AUTOHSCROLL,
            10, 10, 200, 20, hWnd, (HMENU)IDC_USERNAME, NULL, NULL);
        SendMessageW(hUsernameEdit, WM_SETFONT, (WPARAM)hFont, TRUE);

        hPasswordEdit = CreateWindowExW(WS_EX_CLIENTEDGE, L"EDIT", L"",
            WS_CHILD | WS_VISIBLE | WS_BORDER | ES_AUTOHSCROLL | ES_PASSWORD,
            10, 40, 200, 20, hWnd, (HMENU)IDC_PASSWORD, NULL, NULL);
        SendMessageW(hPasswordEdit, WM_SETFONT, (WPARAM)hFont, TRUE);

        CreateWindowW(L"BUTTON", L"登录",
            WS_CHILD | WS_VISIBLE | BS_DEFPUSHBUTTON,
            10, 70, 80, 25, hWnd, (HMENU)IDC_LOGIN, NULL, NULL);
        SendMessageW(hWnd, WM_SETFONT, (WPARAM)hFont, TRUE);

        CreateWindowW(L"BUTTON", L"注册",
            WS_CHILD | WS_VISIBLE | BS_DEFPUSHBUTTON,
            100, 70, 80, 25, hWnd, (HMENU)IDC_REGISTER, NULL, NULL);
        SendMessageW(hWnd, WM_SETFONT, (WPARAM)hFont, TRUE);
        break;
    }
    case WM_COMMAND:
        if (LOWORD(wParam) == IDC_LOGIN) {
            on_login_click();
        } else if (LOWORD(wParam) == IDC_REGISTER) {
            on_register_click();
        }
        break;
    case WM_DESTROY:
        DeleteObject(hFont);
        PostQuitMessage(0);
        break;
    default:
        return DefWindowProcW(hWnd, message, wParam, lParam);
    }
    return 0;
}

// 主窗口过程
LRESULT CALLBACK MainWndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) {
    switch (message) {
    case WM_CREATE:
        InitializeCriticalSection(&csLog);

        hInputEdit = CreateWindowExW(WS_EX_CLIENTEDGE, L"EDIT", L"",
            WS_CHILD | WS_VISIBLE | WS_BORDER | ES_AUTOHSCROLL,
            10, 290, 400, 20, hWnd, (HMENU)IDC_INPUT, NULL, NULL);

        CreateWindowW(L"BUTTON", L"发送",
            WS_CHILD | WS_VISIBLE | BS_DEFPUSHBUTTON,
            420, 290, 80, 25, hWnd, (HMENU)IDC_SEND, NULL, NULL);

        hChatList = CreateWindowW(L"LISTBOX", L"",
            WS_CHILD | WS_VISIBLE | WS_VSCROLL | LBS_NOINTEGRALHEIGHT,
            10, 10, 290, 280, hWnd, (HMENU)IDC_CHATLIST, NULL, NULL);

        hStatus = CreateWindowExW(0, STATUSCLASSNAMEW, L"",
            WS_CHILD | WS_VISIBLE | SBARS_SIZEGRIP,
            0, 0, 0, 0, hWnd, NULL, NULL, NULL);
        SendMessageW(hStatus, SB_SETTEXT, 0, (LPARAM)L"Ready");

        CreateThread(NULL, 0, receive_message, NULL, 0, NULL);
        break;
    case WM_COMMAND:
        if (LOWORD(wParam) == IDC_SEND) {
            on_send_click();
        }
        break;
    case WM_DESTROY:
        connected = FALSE;
        DeleteCriticalSection(&csLog);
        PostQuitMessage(0);
        break;
    default:
        return DefWindowProcW(hWnd, message, wParam, lParam);
    }
    return 0;
}

// WinMain 函数
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) {
    // 初始化客户端状态
    memset(&client_state, 0, sizeof(ClientState));

    // 初始化网络
    if (!InitNetwork()) {
        MessageBoxW(NULL, L"WSAStartup failed!", L"Error", MB_ICONERROR);
        return 1;
    }

    // 连接到服务器
    if (!ConnectToServer("127.0.0.1", 65432)) {
        MessageBoxW(NULL, L"Connection failed!", L"Error", MB_ICONERROR);
        WSACleanup();
        return 1;
    }

    connected = TRUE;

    // 注册登录窗口类
    WNDCLASSEXW login_wc = {0};
    login_wc.cbSize = sizeof(WNDCLASSEXW);
    login_wc.lpfnWndProc = LoginWndProc;
    login_wc.hInstance = hInstance;
    login_wc.lpszClassName = L"LoginWindowClass";
    login_wc.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1);
    login_wc.hCursor = LoadCursorW(NULL, MAKEINTRESOURCEW(IDC_ARROW));
    RegisterClassExW(&login_wc);

    // 创建登录窗口
    hLoginWnd = CreateWindowExW(
        0, L"LoginWindowClass", L"登录",
        WS_OVERLAPPEDWINDOW,
        CW_USEDEFAULT, CW_USEDEFAULT, 250, 150,
        NULL, NULL, hInstance, NULL
    );

    if (hLoginWnd == NULL) {
        MessageBoxW(NULL, L"Login window creation failed!", L"Error", MB_ICONERROR);
        closesocket(clientSocket);
        WSACleanup();
        return 1;
    }

    // 注册主窗口类
    WNDCLASSEXW main_wc = {0};
    main_wc.cbSize = sizeof(WNDCLASSEXW);

    main_wc.lpfnWndProc = MainWndProc;
    main_wc.hInstance = hInstance;
    main_wc.lpszClassName = L"MainWindowClass";
    main_wc.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1);
    main_wc.hCursor = LoadCursorW(NULL, MAKEINTRESOURCEW(IDC_ARROW));
    RegisterClassExW(&main_wc);

    // 创建主窗口
    hMainWnd = CreateWindowExW(
        0, L"MainWindowClass", L"Win32 TCP Client",
        WS_OVERLAPPEDWINDOW,
        CW_USEDEFAULT, CW_USEDEFAULT, 640, 380,
        NULL, NULL, hInstance, NULL
    );

    if (hMainWnd == NULL) {
        MessageBoxW(NULL, L"Main window creation failed!", L"Error", MB_ICONERROR);
        closesocket(clientSocket);
        WSACleanup();
        return 1;
    }

    ShowWindow(hLoginWnd, nCmdShow);
    UpdateWindow(hLoginWnd);

    // 初始隐藏主窗口
    ShowWindow(hMainWnd, SW_HIDE);

    MSG msg;
    while (GetMessageW(&msg, NULL, 0, 0)) {
        TranslateMessage(&msg);
        DispatchMessageW(&msg);
    }

    closesocket(clientSocket);
    WSACleanup();
    return 0;
}